<?php
/**
 * Slipstream :: Highly adaptive dependency injection framework
 * Copyright 2010-2011 Ian Unruh (Xerof3ar)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Slipstream\Activation\Contributor\Collection;

use ArrayObject;
use SplObjectStorage;
use Slipstream\Configuration\AbstractPolicy;
use Slipstream\Activation\ContributorInterface;
use Slipstream\Activation\SessionInterface;

/**
 *
 *
 * @author Ian Unruh (Xerof3ar) <ianunruh@gmail.com>
 * @since Class avaliable since release 1.0
 */
class MergeContributor implements ContributorInterface
{
	/**
	 * Called during an activation session so it can be contributed to
	 *
	 * @param SessionInterface $session
	 * @return void
	 */
	public function onActivation(SessionInterface $session)
	{
		// Merge together policies that are considered equal
		$collectedPolicies = $session->getPolicies();
		$mergedPolicies = new SplObjectStorage();
		foreach($collectedPolicies as $targetPolicy) {
			$collectedPolicies->detach($targetPolicy);
			
			// Determine if any other policies are equal to this policy
			$equalPolicies = new ArrayObject();
			foreach($collectedPolicies as $policy) {
				if($targetPolicy->matches($policy)) {
					$equalPolicies->append($policy);
					$collectedPolicies->detach($policy);
				}
			}
			
			// Merge policies if there any equal ones exist
			if(count($equalPolicies)) {
				$targetPolicy = $targetPolicy->merge($equalPolicies);
			}
			
			// Drop any policies that are disabled
			if(!$targetPolicy->get(AbstractPolicy::OPTION_DISABLED)) {
				$mergedPolicies->attach($targetPolicy);
			}
			
			$collectedPolicies->rewind();
		}
		
		// Add collected policies to the activation session
		$session->addPolicies($mergedPolicies);
	}
}